<?php
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
$myPdo = DbUtils::createPdoInst();
$page_id = MiscUtils::getParam('i', 0);

$items = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . basename(dirname(__FILE__)), NULL, 't.order', 'ASC', NULL, NULL, NULL)->d;

$categories = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_category', NULL, 't.order', 'ASC', NULL, NULL, NULL)->d;

$root = new stdClass();
$root->id = 0;
$root->name = 'ROOT';
$root->parent_id = -1;
__root($items, $root);

$root2 = new stdClass();
$root2->id = 0;
$root2->name = 'ROOT';
$root2->parent_id = -1;
__root($categories, $root2);

function __root($a, $n) {
  for ($i = 0, $il = count($a); $i < $il; $i++) {
    $tmp = $a[$i];
    if ($tmp->parent_id == $n->id) {
      $tmp->_c = array();
      $n->_c[] = $tmp;
      __root($a, $tmp);
    }
  }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
* {
  font-family: Trebuchet MS;
  font-size: 12px;
  padding: 0;
  margin: 0;
}
table.list {
  border-left: 1px solid #666;
  border-top: 1px solid #666;
  font-size: 12px;
  width: 500px;
  padding: 0;
}
table.list td.rowodd {
  height: 25px;
  background-color: #eee;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
  vertical-align: middle;
}
table.list td.roweven {
  height: 60px;
  background-color: #fff;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
  vertical-align: top;
  padding-left: 5px;
}
table.form3 {
  background-color: #fff;
  border: 1px solid #666;
  color: #000;
  padding: 2px;
  cursor: pointer;
  display: inline-block;
  margin: 2px;
  font-weight: bold;
}
table.form3dark {
  background-color: #cecece;
  border: 1px solid #222;
  font-weight: normal;
}
table.form3 td.text {
  width: 35px;
  height: 20px;
  overflow: hidden;
  display: inline-block;
}
table.form3 td.img {
  width: 16px;
  padding-left: 2px;
}
table.form3:hover td {
  background: #fff;
}
table.list tr.none td {
  padding: 0 5px;
  height: 25px;
  background-color: #fff;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
}
.imgbtn {
  background-image: url(images/add.png);
  background-repeat: no-repeat;
  background-position: 5px 2px;
  padding: 5px 5px 5px 30px;
  border: 1px solid #666;
  background-color: #fff;
  cursor: pointer;
  border-radius: 3px;
}
.ok {
  background-image: url(images/ok.png);
  background-size: 24px 24px;
  width: 80px;
}
.cancel {
  background-image: url(images/cancel.png);
  background-size: 24px 24px;
  margin-left: 5px;
  width: 80px;
}
.sub {
  background-image: url(images/add2.png);
  background-size: 20px 20px;
  font-size: 10px;
  margin-top: 2px;
  margin-right: 2px;
}
.up {
  background-image: url(images/u.png);
  background-size: 20px 20px;
  width: 60px;
  font-size: 10px;
  margin-top: 2px;
}
.down {
  background-image: url(images/d.png);
  background-size: 20px 20px;
  width: 60px;
  font-size: 10px;
  margin-top: 2px;
}
.imgbtn:hover {
  background-color: #eee;
}
div.content {
  text-align: center;
  padding: 10px 0;
}
div.content ul {
  padding: 0;
}
div.content li {
  display: inline;
  vertical-align: top;
}
div.content input[type=text] {
  border: 1px solid #ddd;
  border-right: 0;
  height: 30px;
  width: 300px;
}
div.content div {
  border: 1px solid #ddd;
  border-left: 0;
  height: 30px;
  display: table-cell;
  vertical-align: middle;
  cursor: pointer;
}
div.content2 {
  max-height: 200px;
  overflow-x: auto;
}
div.content2 p {
  border-bottom: 1px solid #ddd;
  padding: 5px 0 5px 2px;
  cursor: pointer;
}
div.content2 p:hover {
  background: #eee;
}
ul.hztl2 {
  float: right;
}
ul.hztl2 li {
  display: inline;
  vertical-align: middle;
}
</style>
</head>
<body>
<button class="imgbtn" onclick="add_cat(this, 0);">Display Category</button>
<div>&nbsp;</div>
<table class="list" cellpadding=0 cellspacing=0>
  <?php foreach($root->_c as &$item) { ?>
  <tr>
    <td class="rowodd">
      <table class="form3" cellpadding=0 cellspacing=0>
        <tr>
          <td title="<?php echo $item->name; ?>" class="text"><?php echo $item->name; ?></td>
          <td class="img" onclick="edit_cat(this, JSON.parse('<?php echo htmlspecialchars(json_encode($item)); ?>'));"><img src="images/edit16.png"></img></td>
          <td class="img" onclick="del_cat('<?php echo $item->id; ?>');"><img src="images/delete24.png"></img></td>
        </tr>
      </table>
      <ul class="hztl2">
        <li><button class="imgbtn up" onclick="up('<?php echo $item->id; ?>');">Up</button></li>
        <li><button class="imgbtn down" onclick="down('<?php echo $item->id; ?>');">Down</button></li>
        <li><button class="imgbtn sub" onclick="add_cat(this, '<?php echo $item->id; ?>');">Sub Category</button></li>
      </ul>
    </td>
  </tr>
  <tr>
    <td class="roweven">
      <?php foreach ($item->_c as &$child) { ?>
        <table class="form3 form3dark" cellpadding=0 cellspacing=0>
          <tr>
            <td title="<?php echo $child->name; ?>" class="text"><?php echo $child->name; ?></td>
            <td class="img" onclick="edit_cat(this, JSON.parse('<?php echo htmlspecialchars(json_encode($child)); ?>'));"><img src="images/edit16.png"></img></td>
            <td class="img" onclick="del_cat('<?php echo $child->id; ?>');"><img src="images/delete24.png"></img></td>
          </tr>
        </table>
      <?php } ?>
    </td>
  </tr>
  <?php } ?>
</table>
<div style="height: 350px;">&nbsp;</div>
<script type="text/javascript" src="../../../libs/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script type="text/javascript" src="pop/pop.js"></script>
<script type="text/javascript">
  var _pop, _pop2, _selected = 0;
  var _root = JSON.parse('<?php echo addslashes(json_encode($root)); ?>');
  var _root2 = JSON.parse('<?php echo addslashes(json_encode($root2)); ?>');
  var _items = JSON.parse('<?php echo addslashes(json_encode($items)); ?>');
  var _categories = JSON.parse('<?php echo addslashes(json_encode($categories)); ?>');
  
  function choose_cat(elm, obj) {
    var pos = MyUtils.findPos(elm);
    pos[0] += elm.offsetWidth + 5;
    _pop = new Pop({
      p: pos,
      b: 1,
      t: 'Choose a Category'
    });
    var div, elm;
    div = document.createElement('div');
    div.className = 'content';
    div.innerHTML = '<table  style="margin: 0 auto;" cellpadding=0 cellspacing=0><tr><td><input id="content" type="text" onkeyup="show_tip();" onclick="show_tip();"' + (obj ? ' value="' + obj.name + '"' : '') +'></input></td><td><div onclick="show_cat();"><img src="images/down.png"></img></div></td></tr></table><b>Selected Category:</b> <span id="selected" style="color:red;">None</span><br><br><button class="imgbtn ok" onclick="save_cat(\'' + escapeHtml(JSON.stringify(obj)) + '\');">OK</button><button class="imgbtn cancel" onclick="_selected=0;_pop.close();">Cancel</button>'
    _pop.append(div);
  }

  function add_cat(elm, parent_id) {
    obj = {
      parent_id: parent_id,
      category_id: 0,
      name: '',
    }
    choose_cat(elm, obj);
  }

  function edit_cat(elm, obj) {
    choose_cat(elm, obj);
    select_cat(obj.category_id);
    $('#content')[0].value = obj.name;
  }

  function save_cat(obj_str) {
    try {
      var obj = JSON.parse(obj_str);
    } catch (ex) {
      obj = {
        parent_id: 0,
        category_id: 0,
        name: ''
      };
    }
    obj.category_id = _selected;
    obj.name = $('#content')[0].value;
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=save_cat&q=" + encodeURIComponent(JSON.stringify(obj)),
      success: function(msg){
        _selected = 0;
        _pop.close();
        location.reload();
      }
    });
  }

  function del_cat(id) {
    var r = window.confirm('Are You Sure?');
    if (r) {
      $.ajax({
        type: "POST",
        url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
        data: "action=del_cat&q=" + encodeURIComponent(id),
        success: function(msg){
          location.reload();
        }
      });
    }
  }
  
  function up(id) {
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=up&q=" + encodeURIComponent(id),
      success: function(msg){
        location.reload();
      }
    });
  }

  function down(id) {
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=down&q=" + encodeURIComponent(id),
      success: function(msg){
        location.reload();
      }
    });
  }

  function show_tip() {
    if ($('#content')[0].value == '') {
      show_cat();
      return;
    }
    if (_pop2 && _pop2.is_on()) {
      _pop2.close();
    }
    if (!__is_pop()) {
      return;
    }
    var pos = MyUtils.findPos($('#content')[0]);
    pos[0] += 1;
    pos[1] += $('#content')[0].offsetHeight;
    _pop2 = new Pop({
      p: pos,
      w: $('#content')[0].offsetWidth + 23
    });
    var div, elm;
    div = document.createElement('div');
    div.className = 'content2';
    _categories.sort(function(a, b) {
      return a.name.localeCompare(b.name);
    });
    for (var idx in _categories) {
      var obj = _categories[idx];
      if (obj.name.indexOf($('#content')[0].value) == -1) {
        continue;
      }
      div.innerHTML += '<p onclick="select_cat(\'' + obj.id + '\')">' + hl(obj.name, $('#content')[0].value) + '</p>';
    }
    _pop2.append(div);
  }
  
  function show_cat() {
    if (_pop2 && _pop2.is_on()) {
      _pop2.close();
    }
    var pos = MyUtils.findPos($('#content')[0]);
    pos[0] += 1;
    pos[1] += $('#content')[0].offsetHeight;
    if (_pop2 && _pop2.is_on()) {
      _pop2.close();
    }
    _pop2 = new Pop({
      p: pos,
      w: $('#content')[0].offsetWidth + 23
    });
    var div, elm;
    div = document.createElement('div');
    div.className = 'content2';
    __show_cat(div, _root2, '');
    _pop2.append(div);
  }
  
  function __show_cat(div, node, prefix) {
    if (node.id > 0) {
      div.innerHTML += '<p onclick="select_cat(\'' + node.id + '\')">' + prefix + ')&nbsp;' + hl(node.name, $('#content')[0].value) + '</p>';
    }
    if (prefix == '') {
      prefix = '('
    } else {
      prefix += '-';
      if (prefix != '(') {
        prefix = '&nbsp;&nbsp;&nbsp;' + prefix;
      }
    }
    for (var idx in node._c) {
      var obj = node._c[idx];
      __show_cat(div, obj, prefix + (parseFloat(idx, 10) + 1));
    }
  }

  function __is_pop() {
    var rslt = false;
    for (var idx in _categories) {
      var obj = _categories[idx];
      if (obj.name.toLowerCase().indexOf($('#content')[0].value.toLowerCase()) != -1) {
        rslt = true;
        break;
      }
    }
    return rslt;
  }

  function hl(text, phrase) {
    return text.toLowerCase().replace(new RegExp(phrase.toLowerCase(), "g"), '<span style="background:yellow;">' + phrase.toLowerCase() + '</span>');
  }

  function escapeHtml(text) {
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
  }

  function select_cat(id) {
    var elm, name = __get_cat(id);
    _selected = id;
    $('#content')[0].value = name;
    MyUtils.removeChildElements($('#selected')[0]);
    if (!name) {
      $('#selected')[0].appendChild(document.createTextNode('None'));
      $('#selected')[0].style.color = 'red';
    } else {
      $('#selected')[0].appendChild(document.createTextNode(name));
      $('#selected')[0].style.color = 'black';
      elm = document.createElement('a');
      elm.style.marginLeft = '5px';
      elm.href = '#';
      elm.appendChild(document.createTextNode('Unselect'));
      elm.onclick = function() {
        var tmp = $('#content')[0].value;
        select_cat(0);
        $('#content')[0].value = tmp;
      };
      $('#selected')[0].appendChild(elm);
    }
  }

  function __get_cat(id) {
    for (var idx in _categories) {
      var obj = _categories[idx];
      if (obj.id == id) {
        return obj.name;
      }
    }
    return null;
  }
  
  $(function(){
    
  });
</script>
</body>
</html>